package com.ziq.zcamp.dialog

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.*
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ziq.base.base.BaseDialog
import com.ziq.base.extension.binding
import com.ziq.base.extension.click
import com.ziq.base.utils.SystemBarUtil
import com.ziq.zcamp.bean.place.AreaItem
import com.ziq.zcamp.bean.place.FilterAreaData
import com.ziq.zcamp.databinding.DialogCampListFilterAreaBinding
import com.ziq.zcamp.place.*
import com.ziq.zcamp.view.layoutmanager.FilterAreaCategoryContentGridLayoutManager

class CampListFilterAreaDialog(context: Context, val mViewModel: PlaceListFragmentViewModel, val mPlaceAreaViewModel: CampListAreaViewModel, val onPlaceSelect: OnPlaceSelectResultListener) : BaseDialog(context) {



    private val binding: DialogCampListFilterAreaBinding by binding()

    override fun initHeight(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }
    override fun initWidth(): Int {
        return ViewGroup.LayoutParams.MATCH_PARENT
    }

    var filterAreaCategoryContentAdapter : CampListFilterAreaCategoryContentAdapter? = null
    var isAreaCategoryClick = false

    override fun onStart() {
        super.onStart()
        window?.decorView?.let {
            SystemBarUtil.immerseStatusBar(window, statusBarIsLight = true)
            window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.root.fitsSystemWindows = true // 会使得root 键盘弹出的时候增加 paddingbottom
        binding.root
        binding.btnAreaInfo.click {
            dismiss()
        }

        binding.btnClose.click {
            dismiss()
        }

        mViewModel.selectedItem.value?.let { item->
            if(item.id != -1L){
                binding?.tvFilterArea?.text = item.name
            } else {
                binding?.tvFilterArea?.text = "全国"
            }
        }

        initFilterArea()

    }


    fun initFilterArea(){
            filterAreaCategoryContentAdapter = CampListFilterAreaCategoryContentAdapter(context)
            binding?.rvAreaCategoryContent?.layoutManager = FilterAreaCategoryContentGridLayoutManager(context, 3, filterAreaCategoryContentAdapter, filterAreaCategoryContentAdapter)
            binding?.rvAreaCategoryContent?.adapter = filterAreaCategoryContentAdapter
            filterAreaCategoryContentAdapter?.onPlaceSelectResultListener = object : OnPlaceSelectResultListener {
                override fun onPlaceSelect(item: AreaItem, source: String) {
                    onPlaceSelect.onPlaceSelect(item, source)
                    dismiss()
                }
            }

            binding?.rvAreaCategoryContent?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    if(isAreaCategoryClick){
                        return
                    }
                    updateAreaCategory()
                }

                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if(newState == RecyclerView.SCROLL_STATE_IDLE){
                        isAreaCategoryClick = false
                    }
                }
            })

        binding.fastIndexView.updateUISetting(
            textColor = Color.parseColor("#333333"),
            selectTextColor = Color.parseColor("#FFFFFF"),
            selectBackgroundColor = Color.parseColor("#000000"),
        )

            binding?.fastIndexView?.onSelectedListener = { groupPosition, text->
                val targetPosition = filterAreaCategoryContentAdapter?.getCityGroupPosition(groupPosition)
                targetPosition?.let {
                    isAreaCategoryClick = true
                    binding?.rvAreaCategoryContent?.scrollToPosition(it)
                    (binding?.rvAreaCategoryContent?.layoutManager as FilterAreaCategoryContentGridLayoutManager).scrollToPositionWithOffset(it, 0)
                }
            }
            binding?.fastIndexView?.onEventListener = { text, action, actionCenterY ->
                if(action == MotionEvent.ACTION_MOVE){
                    binding?.tvFilterAreaTips?.translationY = actionCenterY
                    binding?.tvFilterAreaTips?.visibility = View.VISIBLE
                    binding?.tvFilterAreaTips?.text = "$text"
                } else if(action == MotionEvent.ACTION_UP){
                    binding?.tvFilterAreaTips?.visibility = View.GONE
                    isAreaCategoryClick = false
                }
            }

        binding.btnProvinces.click {
            val targetPosition = filterAreaCategoryContentAdapter?.countGroupRangeItem(0, filterAreaCategoryContentAdapter?.provincesStartGroupPosition?:0)
            targetPosition?.let {
                binding?.rvAreaCategoryContent?.scrollToPosition(it)
                (binding?.rvAreaCategoryContent?.layoutManager as FilterAreaCategoryContentGridLayoutManager).scrollToPositionWithOffset(it, 0)
            }
        }

        binding.btnHotCity.click {
            val targetPosition = filterAreaCategoryContentAdapter?.countGroupRangeItem(0, filterAreaCategoryContentAdapter?.hotCityStartGroupPosition?:0)
            targetPosition?.let {
                binding?.rvAreaCategoryContent?.scrollToPosition(it)
                (binding?.rvAreaCategoryContent?.layoutManager as FilterAreaCategoryContentGridLayoutManager).scrollToPositionWithOffset(it, 0)
            }
        }


        mPlaceAreaViewModel.filterAreaData.observe(this) {
            updateCityData(it)
        }
    }


    fun updateAreaCategory(){
        val layoutManager: GridLayoutManager?  = binding?.rvAreaCategoryContent?.layoutManager as GridLayoutManager?
        if(layoutManager != null){
            val firstVisible = layoutManager.findFirstVisibleItemPosition()
            val category = filterAreaCategoryContentAdapter?.getFirstVisibleCategory(firstVisible)
            category?.let {
                if(
//                    it.category == PlaceAreaViewModel.area_category_hot_city ||
                    it.category == PlaceAreaViewModel.area_category_city ||
                    it.category == PlaceAreaViewModel.area_category_city_item ){
                    binding?.fastIndexView?.visibility = View.VISIBLE
                    if(it.category == PlaceAreaViewModel.area_category_hot_city){
                        binding?.fastIndexView?.setTouchIndex(0)
                    } else {
                        binding?.fastIndexView?.setTouchGroup(it.name)
                    }
                    binding?.btnProvinces?.isVisible = filterAreaCategoryContentAdapter?.hasProvinces == true
                    binding?.btnHotCity?.isVisible = filterAreaCategoryContentAdapter?.hasHotCity == true

                }else{
                    binding?.fastIndexView?.visibility = View.GONE
                    binding?.btnProvinces?.isVisible = false
                    binding?.btnHotCity?.isVisible = false
                }
            }
        }
    }

    fun updateCityData(filterAreaData: FilterAreaData?){
        var groupList = parseCityData(filterAreaData)
        filterAreaCategoryContentAdapter?.setData(mPlaceAreaViewModel.filterAreaData.value, groupList)
        filterAreaCategoryContentAdapter?.updateSelectedId(mViewModel.selectedItem.getValue()?.id)
        val groupString = mutableListOf<String>()
        for (label in PlaceAreaViewModel.GROUP_LABEL){
            if(groupList?.containsKey(label) == true){
                groupString.add(label)
            }
        }
        binding?.fastIndexView?.setData(groupString)
    }

    fun parseCityData(filterAreaData: FilterAreaData?): MutableMap<String, MutableList<AreaItem>>?{
        var groupList: MutableMap<String, MutableList<AreaItem>>? = null
        if(filterAreaData?.cities?.isNotEmpty() == true){
            groupList = mutableMapOf()
            for (city in filterAreaData.cities!!){
                if(city.capital_letter != null){
                    var initial = city.capital_letter!!.toUpperCase()
                    if(!PlaceAreaViewModel.GROUP_LABEL.contains(initial)){
                        initial = "#"
                    }
                    if(groupList.containsKey(initial)){
                        groupList[initial]?.add(city)
                    } else {
                        groupList[initial] = mutableListOf(city)
                    }
                }
            }
        }
        return groupList
    }


}